package com.changzhi.controller;

import com.changzhi.common.exception.ServiceException;
import com.changzhi.common.util.Result;
import com.changzhi.util.ObsUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description:测试
 * @author: 小落
 * @date: 2020年10月10日
 */
@Slf4j
@CrossOrigin
@RestController
@RequestMapping("upload")
public class UploadController {


	@PostMapping("upload")
	public Result upload(@RequestParam("file") MultipartFile file,String dirName, String pwd, String accountId) throws IOException {
		checkPwd(pwd);
		if(StringUtils.isBlank(dirName)){
			dirName = "other";
		}
		String fileName = String.format("%s_%s_%d.jpg", accountId, System.currentTimeMillis(), (int)((Math.random() * 9 + 1) * 100000));
		Map<String, String> map = new HashMap<>();
		long t = System.currentTimeMillis();
		map.put("url", ObsUtil.upload(dirName, fileName, file.getInputStream()));
		log.error("upload:耗时={}", System.currentTimeMillis()-t);
		return Result.success(map);
		/*List<String> list = new ArrayList<>();
		for (MultipartFile file : files) {
			String fileName = String.format("%s_%s.jpg", accountId, System.currentTimeMillis());
			list.add(ObsUtil.upload(dirName, fileName, file.getInputStream()));
		}
		return Result.success(list);*/
	}


	private void checkPwd(String pwd) {
		if(!"8704".equals(pwd)){
			throw new ServiceException("密码错误！");
		}
	}
}
